package sm.hibernate.type;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.usertype.ParameterizedType;

import sm.codec.type.RC;
import sm.codec.type.Struct;
import sm.def.Type;

import com.google.gson.Gson;

public class RCArrayType extends AbstractRCCompositeType implements
		ParameterizedType {

	private Object fieldTypeDef;

	@Override
	public void setParameterValues(Properties parameters) {
		String jsonArray = parameters.getProperty("fieldTypeDef");
		if (jsonArray != null) {
			Gson gson = new Gson();
			fieldTypeDef = gson.fromJson(jsonArray, Object.class);
		}
	}

	@Override
	public Class returnedClass() {
		return List.class;
	}

	@Override
	public Object deepCopy(Object value) throws HibernateException {
		return value;

	}

	@Override
	protected Object rcToValue(RC rc, Object owner) {
		Object value = rc;
		if (rc != null) {
			List<Object> values = rc.getValues();
			if (values != null && values.size() == 1) {
				value = values.get(0);
				if (value instanceof Struct) {
					Struct struct = (Struct) value;
					if (struct.getType() == Type.ARRAY_TYPE) {
						value = RCTypeHelper.arrayToList(struct.getValue(),
								fieldTypeDef);
					}
				}
			}
		}

		return value;
	}

	@Override
	protected RC valueToRC(Object value) {
		RC rc = null;
		if (value != null) {
			if (value instanceof RC) {
				rc = (RC) value;
			} else {
				if (value instanceof List) {
					List<Object> array = (List<Object>) value;
					List<Object> values = RCTypeHelper.listToArray(array,
							fieldTypeDef);
					value = new Struct(values, Type.ARRAY_TYPE);
				}
				List<Object> values = new ArrayList<Object>();
				values.add(value);
				rc = new RC(values);
			}
		}

		return rc;

	}

}
